package student.aistar.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import student.aistar.model.bo.Result;
import student.aistar.model.dto.ProductInfoDTO;
import student.aistar.model.entity.*;
import student.aistar.service.*;
import student.aistar.service.impl.CommentImgService;
import student.aistar.service.impl.CommentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Auther: zhugefeng
 * @Date:2021/9/26 19:42
 **/
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @Autowired
    private IIndexService iIndexService;

    @Autowired
    private ICartService cartService;

    @Autowired
    private IProductParameterService productParameterService;

    @Autowired
    private ItemCFService itemCFService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CommentImgService commentImgService;

    @Autowired
    private RedisTemplate redisTemplate;

    private RestHighLevelClient restHighLevelClient;

    public ProductController(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @GetMapping("/find")
    public String find(String productName, Model model, HttpServletRequest request) {
        List<Navclass> navClassList = iIndexService.navClassList();
        request.setAttribute("navClassList", navClassList);
        model.addAttribute("productName", productName);

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            List<Product> list = new ArrayList<>();
            ArrayList<Integer> lists = itemCFService.result(user.getUserId());
            int productlistsize = 0;
            if (lists != null && lists.size() > 0) {
                list = itemCFService.recommend(lists);
                productlistsize = list.size();
                request.setAttribute("productlist", list);
                request.setAttribute("productlistsize", productlistsize);
            } else {
                request.setAttribute("productlist", "nulls");
            }
//            System.out.println(productlistsize);
        }

        return ("mi/product/search_load");
    }
    @GetMapping("/test")
    public String te(){
        return "mi/product/test";
    }

//    @GetMapping("search2")
//    public String search2(){
//        return ("mi/product/search2");
//    }

    @PostMapping("/search")
    public String search(HttpServletRequest request, String productName, Integer categoryId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "8") Integer pageSize) {
        List<Navclass> navClassList = iIndexService.navClassList();
        request.setAttribute("navClassList", navClassList);
        PageInfo<Product> productPageInfo = productService.getProduct(productName, categoryId, pageNum, pageSize);
        List<Category> categoryList = productService.getAllCategory();

        request.setAttribute("pname", productName);
        request.setAttribute("productPageInfo", productPageInfo);
        request.setAttribute("categoryList", categoryList);
        request.setAttribute("indexColor", categoryId);

        return ("mi/product/search2");
    }
    @GetMapping("/search/query02")
    public String query02(HttpServletRequest request, String text) throws IOException {
        Request request1 = new Request("GET", "products/_search");
        request1.setJsonEntity(String.format("{" +
                "  \"_source\": [\"product_id\",\"product_name\",\"price\",\"pic_img\",\"category_id\",\"introduce\",\"tags\",\"so\"]," +
                "  \"query\": {" +
                "    \"multi_match\": {" +
                "      \"query\": \"%s\"," +
                "      \"fields\": [\"product_name\",\"introduce\",\"tags\",\"so\"]" +
                "    }" +
                "  }" +
                "}", text));
        Response response = restHighLevelClient.getLowLevelClient().performRequest(request1);

        JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));

        JSONArray hits = jsonObject.getJSONObject("hits").getJSONArray("hits");

        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < hits.size(); i++) {
            Product product = new Product();
            JSONObject hit = hits.getJSONObject(i);
            JSONObject sources = hit.getJSONObject("_source");
            product.setProductId(sources.getInteger("product_id"));
            product.setProductName(sources.getString("product_name"));
            product.setPrice(sources.getFloat("price"));
            product.setPicImg(sources.getString("pic_img"));
            product.setCategoryId(sources.getInteger("category_id"));
            product.setIntroduce(sources.getString("introduce"));
            product.setTags(sources.getString("tags"));

            productList.add(product);
        }
        request.setAttribute("productES", productList);
        return ("mi/product/search");
    }

    @GetMapping("/parameter")
    public String parameter(HttpServletRequest request, Integer productId) {
        ProductInfoDTO productInfoDTO = productService.productInfo(productId);
        Parameters parameters = productParameterService.getParameterByProductId(productId);
        request.setAttribute("productInfoDTO", productInfoDTO);
        request.setAttribute("parameters", parameters);
        List<Navclass> navClassList = iIndexService.navClassList();
        request.setAttribute("navClassList", navClassList);
        return ("mi/product/parameter");
    }

    @GetMapping("/comment")
    public String comment(HttpServletRequest request) {
        List<Navclass> navClassList = iIndexService.navClassList();
        request.setAttribute("navClassList", navClassList);
        List<Comment> commentList = commentService.findByState("1");
        request.setAttribute("commentList", commentList);
        List<Comment> comments = commentService.findByState("2");
        request.setAttribute("comments", comments);
        List<CommentImg> commentImgs = commentImgService.findCommentImgList();
        request.setAttribute("commentImgs", commentImgs);

        return ("mi/product/comment");
    }

    @PostMapping("/comments")
    @ResponseBody
    public Result comments(HttpServletRequest request, String content, String id) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String userid = String.valueOf(user.getUserId());
        String username = user.getUserName();
        Comment comment = new Comment();
        comment.setUserid(userid);
        comment.setNickname(username);
        comment.setContent(content);
        comment.setLikenum(0);
        comment.setParentid(id);
        comment.setState("2");
        comment.setUserimg(user.getUserImg());
        List<Comment> commentList = commentService.findByState("1");
        List<Comment> comments = commentService.findByState("2");
        comment.setAid(String.valueOf(comments.size() + commentList.size() + 1));

        commentService.saveComment(comment);

        return new Result("200", comments.size() + commentList.size() + 1);
    }

    @PostMapping("/good")
    @ResponseBody
    public Result good(HttpServletRequest request, String id) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //把用户点赞信息保存到redis中
        Object result = redisTemplate.opsForValue().get("likenum_" + id);
//        System.out.println(result);
        if (result != null) {
            return new Result("300", "已经点过了");
        } else {

            commentService.updateCommentLikenum(id);
            //点赞成功,保存信息
            redisTemplate.opsForValue().set("likenum_" + id, 1);

            return new Result("200", "还没点过");
        }
    }


    /**
     * 这里还要分两种情况, 用户登录情况, 用户没登陆情况
     *
     * @param model
     * @param productId
     * @param para      传过来的全参
     * @param proName   传过来只是部分产品名
     * @param paraPrice
     * @return
     */
    @GetMapping("/addTip")
    public String addSuccessTip(HttpSession session, Model model, Integer productId, String para, String proName, Double paraPrice) {
        List<Navclass> navClassList = iIndexService.navClassList();
        model.addAttribute("navClassList", navClassList);

        User user = (User) session.getAttribute("user");
        productService.addSuccessTip(user, productId, para, proName, paraPrice);


        Cart cart = cartService.selectByUserIdAndProductId(user.getUserId(), productId, para);
        model.addAttribute("cart", cart);

        return "mi/product/add_success_Tip";
    }


    //概述页
    @GetMapping("/overview")
    public String overview(Model model, Integer productId) {
        List<Navclass> navClassList = iIndexService.navClassList();
        model.addAttribute("navClassList", navClassList);
        ProductInfoDTO productInfoDTO = productService.productInfo(productId);
        List<Overviewpage> overviewpageList = productService.selectOverViewPageByProductId(productId);
        model.addAttribute("productInfoDTO", productInfoDTO);
        model.addAttribute("overviewpageList", overviewpageList);
        return ("mi/product/overview_page");
    }


}
